import { useEffect, useMemo, useState } from 'react'
import style from './index.module.less'
import PageComponent from '@components/pageComponent'
import CardPicker from '@components/cardPicker'
import { Button, Form, Toast } from 'antd-mobile'
import { CheckOutline } from 'antd-mobile-icons'
import { awaitWrap } from '@src/assets/js/tool'
import { logout, setUserInfo } from '@src/redux/reducers/basic'
import { submitRequest, logoutRequest } from './ajax'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
// import { setList } from '@src/redux/reducers/pages'
// import uuid from 'uuid'
import { useHistory } from 'react-router-dom'
import { root } from '@src/assets/js/config'

const { Item } = Form

async function logoutHandle (callback) {
  Toast.show({
     icon: 'loading',
    content: '退出中',
    duration: 0
  })
  const [e] = await awaitWrap(logoutRequest())
  if (e === null) {
    Toast.clear()
    callback()
  }
}

// async function initInfo (setInfo) {
//   Toast.show({ content: '加载中', icon: 'loading', duration: 0 })
//   const [e, d] = await awaitWrap(getIdentityInfoRequest())
//   if (e === null) {
//     Toast.clear()
//     if (d !== null) {
//       setInfo(d)
//       if (!d.license || !d.name) {
//         Toast.show({ content: '账号身份证信息缺失', duration: 2000 })
//       }
//     } else {
//       Toast.show({ content: '账号身份证信息缺失', duration: 2000 })
//     }
//   }
// }

// 验证身份信息与预留信息是否相同
// function validateIdInfo(
//   idCardInfo,
//   idCard,
//   name,
// ) {
//   if (idCardInfo.license !== idCard || idCardInfo.name !== name) {
//     Toast.fail('当前身份证与账号身份证信息不匹配');
//     return false;
//   }
//   return true;
// }

// 提交
async function submitHandle (submitable, front, back, userInfo, h, dispatch) {
  if (!submitable || front === null || back === null) {
    return undefined
  }
  // if (!validateIdInfo(info, front.info.num, front.info.name)) {
  //   return undefined;
  // }
  Toast.show({ content: '提交中', icon: 'loading', duration: 0  })
  const [e] = await awaitWrap(submitRequest(front.info.name, front.info.num, front.id, back.id))
  if (e === null) {
    Toast.clear()
    const u = JSON.parse(JSON.stringify(userInfo))
    if (u.is_auth === 0) {
      u.is_auth = 1
      u.realname = front.info.name
      dispatch(setUserInfo(u))
    }
    h.replace(`${root}/gate/home`)
    // dispatch(setList([{ element: 'home', title: '首页', id: uuid() }]))
  }
}
function Main () {
  // const [info, setInfo] = useState({})
  const [front, setFront] = useState()
  const [back, setBack] = useState()
  const [agree, setAgree] = useState(false)
  const userInfo = useAppSelector(state => state.basic.userInfo)
  const dispatch = useAppDispatch()
  const h = useHistory()
  const { name, license } = useMemo(() => {
    if (front && front.info) {
      const info = front.info
      return {
        name: info.name,
        license: info.num
      }
    }
    return {
      name: '',
      license: ''
    }
  }, [front])
  useEffect(() => {
    // initInfo(setInfo)
  }, [])
  return (
    <PageComponent title='实名认证' onBack={() => {
      logoutHandle(() => {
        dispatch(logout())
        // setTimeout(() => {
        //   h.replace(`${root}/gate/home`)
        // }, 0)
      })
    }}>
      <div className={style.container}>
        <div className={style.notice}>最长边不超过6000像素，单张图片大小不超过6M，建议控制在1.5M以内。</div>
        <div className={style.pics}>
          <CardPicker isFront value={front} onChange={setFront} />
          <CardPicker value={back} onChange={setBack} />
        </div>
        <div className={style['sub-title-line']}>根据网络仲裁规则规定，需要身份与账号绑定。</div>
        <div className={style.info}>
          <Form layout='horizontal'>
            <Item label='姓名' name='name'>
              <div className={style.text}>{name || '无'}</div>
            </Item>
            <Item label='身份证' name='license'>
              <div className={style.text}>{license || '无'}</div>
            </Item>
          </Form>
        </div>
        <div className={style['agree-line']} onClick={() => setAgree(!agree)}>
          <div className={style.checkbox}>
            {agree && <CheckOutline />}
          </div>
          <div className={style['agree-text']}>
            <span>我同意遵守</span>
            <a onClick={(e) => { e.stopPropagation() }}>《授权须知》</a>
          </div>
        </div>
        <div className={style.btn}>
          <Button color='primary' block disabled={!front || !back || !agree} onClick={() => submitHandle(agree, front, back, userInfo, h, dispatch)}>提交</Button>
        </div>
      </div>
    </PageComponent>
  )
}

export default Main
